//
//  SuppliersViewController.swift
//  weile
//
//  Created by LKM on 17/1/16.
//  Copyright © 2017年 LKM. All rights reserved.
//

import UIKit

class SuppliersViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource  {
    
    @IBOutlet weak var tableview: UITableView!
    
    @IBOutlet weak var searchBox: UIView!
    @IBOutlet weak var lbl_search: UILabel!
    @IBOutlet weak var classSelectsView: UIScrollView!
    
    
    var mListFooterLoadView :ListFooterLoadView!
    var refreshControl:UIRefreshControl!
    var data:ArticlesTo?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        ViewHelp.setOnClickListening(searchBox, self, #selector(onSearchBoxClick))
        searchBox.layer.cornerRadius = 15;
        
        mListFooterLoadView = ListFooterLoadView.createView();
        self.tableview.tableFooterView=mListFooterLoadView;
        
        self.tableview.register(UINib(nibName:"SuppliersItem", bundle: nil), forCellReuseIdentifier: "SuppliersItem")
        
        //tableview参数设置
        tableview.rowHeight = SuppliersItem.getHeigth()//98.7//8+82+8+0.7
        tableview.separatorStyle = .none
        tableview.contentInset = UIEdgeInsetsMake(0, 0, MainTabBarHeight, 0)
        tableview.scrollIndicatorInsets = tableview.contentInset
        tableview.delegate=self;
        tableview.dataSource = self;
        //tableview参数设置  end
        
        // 添加刷新控件
        refreshControl = UIRefreshControl()
        //        refreshControl.attributedTitle = NSAttributedString(string: "松开后自动刷新")
        tableview.addSubview(refreshControl)
        refreshControl.addTarget(self, action: #selector(loadData(_:)), for: .valueChanged)
        // 添加刷新控件 end
        
        if loadData(false){
            refreshControl.beginRefreshing()
        }
        
        // Do any additional setup after loading the view.
    }
    
    func onSearchBoxClick(){
        ActivityRequest.goSearchViewController(self.navigationController!)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: false)
    }
    
    var selectClassId:String! = ""{
        
        didSet{
            loadData(false);
        }
    }
    
    
    
    var listData: [ArticlesItemTo] = Array();//
    var curPage = 1;//第一开始
    var isLoadIng = false;//是否加载中
    var isLoadAppending = false;//是否加载更多数据
    var hasMoreData=true;//是否有更多数据
    
    @discardableResult
    func loadData(_ isLoadAppend :Bool) -> Bool{
        if isLoadIng {
            return isLoadAppend == isLoadAppending;
        }
        self.isLoadAppending=isLoadAppend;
        isLoadIng=true
        
        if(isLoadAppend){
            mListFooterLoadView.setAppending()
        }else{
            mListFooterLoadView.setRefreing()
        }
        
        let taskSerialNumber=Api.getSuppliers(preTaskSerialNumber: nil,page: isLoadAppend ? (curPage + 1) : 1, mainId: "",classId:selectClassId ?? ""){ (re:ResponEntity) in
            self.isLoadIng=false;
            if(re.isSuccess()){
                self.data = re.data as? ArticlesTo;
                self.setupTitlesView(self.data?.channellist ?? [ArticlesChannesTo]() )
                
                
                //数据是那些----
                let hasListData = !(CollectionHelp.isEmpty( self.data?.articlelist )) //!(self.data?.prolist == nil);
                if(self.isLoadAppending){
                    self.curPage += hasListData ? 1 : 0;
                }else{
                    self.listData.removeAll();
                    self.curPage = 1;
                }
                self.listData += self.data?.articlelist ?? Array();
                
                self.hasMoreData = hasListData
                //没有更多数据了
                self.mListFooterLoadView.setNone(hasNextPage: hasListData)
                //数据是那些----end
                
                self.tableview.reloadData()
            }else{
                ViewHelp.showTipsView(containView: self.view, tips: re.msg);
            }
            self.refreshControl.endRefreshing()
        }
        taskAlls.append(taskSerialNumber);
        
        return true;
    }
    
    var taskAlls = [Int]();
    deinit {
        //界面退出肯定就不登陆咯
        Api.destroyTask(taskSerialNumbers: taskAlls);
    }
    
    
    //_____顶部分类
    // 标签
    weak var titlesView = UIView()
    //标签下 底部颜色条指示器
    weak var indicatorView = UIView()
    ///标签 当前选中的按钮
    weak var selectedButton = UIButton()
    
    let kTitlesViewH :CGFloat = 30
    //顶部
    let kTitlesViewY :CGFloat = 0;//20 因为xib了
    /// 顶部标签栏
    func setupTitlesView(_ classss : [ArticlesChannesTo]?) {
        if ( self.titlesView != nil ){
            return ;//已经实例化过了
        }
        
        var classs = classss
        
        let allClass = ArticlesChannesTo.init(jsons: [:])!
        allClass.Title = "全部"
        allClass.Id = ""
        
        classs?.insert(allClass, at: 0);
        
        let kIndicatorViewH :CGFloat = 2.0
        /// 屏幕的宽
        let SCREENW = UIScreen.main.bounds.size.width
        
        //        let topview = UIView()
        //        topview.frame = CGRect(x: 0, y: 0, width: SCREENW, height: kTitlesViewY)
        //        topview.backgroundColor = UIColor.clear
        //        view.addSubview(topview)
        
        
        // 顶部背景
        let bgView = UIView()
        bgView.frame = CGRect(x: 0, y: kTitlesViewY, width: SCREENW, height: kTitlesViewH)
        //        bgView.backgroundColor=UIColor.red
        classSelectsView.addSubview(bgView)
        // 标签
        let titlesView = UIView()
        titlesView.backgroundColor = UIColor.clear
        titlesView.frame = CGRect(x: 0, y: 0, width: SCREENW , height: kTitlesViewH)
        bgView.addSubview(titlesView)
        self.titlesView = titlesView
        
        
        //内部子标签
        let count = CollectionHelp.size(classs)//childViewControllers.count
        let width =  CGFloat( Double(titlesView.width)/min(5.5, Double(count)) );// titlesView.width / CGFloat(count)
        let height = titlesView.height
        
        //底部颜色指示器
        let indicatorView = UIView()
        //        67, 153, 165
        indicatorView.backgroundColor = UIColor(red: 67/255, green: 153/255, blue: 165/255, alpha: 1)//R.colors.base_color
        indicatorView.height = kTitlesViewH//kIndicatorViewH
        indicatorView.width = width
        indicatorView.y = 0//kTitlesViewH - kIndicatorViewH
        indicatorView.tag = -1
        self.indicatorView = indicatorView
        //底部指示器
        titlesView.addSubview(indicatorView)
        
        
        self.classSelectsView.contentSize.width = (width) * CGFloat(count)
        
        //        27, 70, 79
        let selectColor=UIColor(red: 27/255, green: 70/255, blue: 79/255, alpha: 1);
        for index in 0..<count {
            let button = UIButton()
            button.height = height
            button.width = width
            button.x = CGFloat(index) * width
            button.tag = index
            let cv = classs?[index];
            button.setTag(&R.id.tag, cv)
            button.titleLabel!.font = UIFont.systemFont(ofSize: 13)
            button.setTitle(cv?.Title ?? "", for: UIControlState())
            button.setTitleColor(selectColor, for: UIControlState())//#1B464F
            button.setTitleColor(UIColor.white, for: .disabled)
            button.addTarget(self, action: #selector(titlesClick(_:)), for: .touchUpInside)
            titlesView.addSubview(button)
            //默认点击 默认要的那个
            if index == HomeViewController.SelectIndex {
                button.isEnabled = false
                selectedButton = button
                //让按钮内部的Label根据文字来计算内容
                //                button.titleLabel?.sizeToFit()
                //                indicatorView.width = button.titleLabel!.width
                indicatorView.centerX = button.centerX
            }
        }
        
    }
    
    /// 标签上的按钮点击
    func titlesClick(_ button: UIButton) {
        // 修改按钮状态
        selectedButton!.isEnabled = true
        button.isEnabled = false
        selectedButton = button
        // 让标签执行动画
        UIView.animate(withDuration: kAnimationDuration, animations: {
            //            self.indicatorView!.width = self.selectedButton!.titleLabel!.width
            self.indicatorView!.centerX = self.selectedButton!.centerX
        })
        //滚动,切换子控制器
        let o = button.getTag(&R.id.tag) as! ArticlesChannesTo
        selectClassId = o.Id//"\(o.Id)";
        //        LKMLog("=====selectClassId \(selectClassId)")
    }
    
    //______顶部分类_end
    
    
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    // MARK: - UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.listData.count
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let homeCell = tableView.dequeueReusableCell(withIdentifier: "SuppliersItem") as! SuppliersItem//ArticlesItem
        homeCell.selectionStyle = .default
        homeCell.curIndex = (indexPath as NSIndexPath).row;
        homeCell.mArticlesItemTo = self.listData[(indexPath as NSIndexPath).row]
        
        let count:Int=self.tableView( tableView, numberOfRowsInSection:1);
        if(indexPath.row+1>=count){
            //加载更多数据
            if hasMoreData{
                //一般到显示倒数第二个就会去加载
                loadData(true);
            }
            
        }
        
        
        return homeCell
    }
    // MARK: - UITableViewDelegate
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true);//去掉选择后的 选定效果
        
        let o = self.listData[(indexPath as NSIndexPath).row]
        ActivityRequest.goArticleDetailController(navigationController!,o.Id ?? "");
    }
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
